/* 
 * File:   client.c
 * Author: champion
 *
 * Created on 27 octobre 2009, 17:49
 */


#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <rpc/rpc.h>
#include "myFtp.h"
#include "tools.h"


/*
 * Programme principale
 */

int main(int argc, char** argv) {

	int *intResult,out,flag;
        char **charResult,*charArg,** fileResult;
        bool_t * boolResult;
        char buffer[256];
        char cmd[256];
        char args[256];
        char* result;
        char path[MAXPATHLEN];
        authparms *unixParms=NULL;
        uid_t uid;
        gid_t gid, aup_gids[16];
        int len;
	int aux;
        AUTH *auth;

	CLIENT *cl;

	if(argc < 2){
                fprintf(stderr,"Usage: %s server [username][Uid,Gid] \n",argv[0]);
		exit(1);
	}

        // Construction du client
	cl = clnt_create(argv[1],PROG,VERS,"tcp");
	if ( cl == NULL ){
		clnt_pcreateerror(argv[1]);
		exit(1);
	}

        // Authentification par défaut dans le cas où l'utilisateur
        // n'a pas envoyer de username pour la connexion
        if(argc == 2)
            auth = authunix_create_default();
        else if(argc==4){  // Authentification faite en envoyant le UID et le Gid

	  aux = atoi(argv[2]);
	  uid = (uid_t)aux; 	
	  aux = atoi(argv[3]);
          gid = (gid_t)aux;
          aup_gids[0] = gid;          
          
        if ((len = getgroups(NGRPS, aup_gids)) < 0) {
           printf("failed in getgroups()!!\n");
            exit(2);
        }else
            len = (len > 16) ? 16 : len;

        /* Initialisation de authunix_create() avec les paramètres reçus */
          auth = authunix_create(argv[1], uid, gid,len, aup_gids);

          if (auth == (AUTH *)NULL) {
            fprintf(stderr, "authunix_create failed!!\n");
            exit(1);
           }
	    	
	}
        else{
        //Chercher le uid et le gid chez le serveur
          unixParms=connect_1(&argv[2], cl);
          if(unixParms->uid == -1 && unixParms->gid == -1){
              fprintf(stderr, " Authentification échouée!!\n");
              exit(2);
          }
          // Récuperer le uid et le gid de l'utilisateur
          uid = unixParms->uid;
          gid = unixParms->gid;
          aup_gids[0] = unixParms->gid;          
          
        if ((len = getgroups(NGRPS, aup_gids)) < 0) {
           printf("failed in getgroups()!!\n");
            exit(2);
        }else
            len = (len > 16) ? 16 : len;

        /* Initialisation de authunix_create() avec les paramètres reçus */
          auth = authunix_create(argv[1], uid, gid,len, aup_gids);

          if (auth == (AUTH *)NULL) {
            fprintf(stderr, "authunix_create failed!!\n");
            exit(1);
          }
        }

        cl->cl_auth = auth;

        printf("\n");

        /*
         * Execution des commandes par l'utilisateur
        */

        while(1){
        flag=0;
        printf("[myFtp@user ~]$ ");
        fgets(buffer,255,stdin);
        split(buffer, cmd, args,' ');
        
    //  Exécution de PWD
	if(strcmp(cmd,"pwd")==0){
            charResult = pwd_1((void *)NULL, cl);
            if (charResult == NULL){
                    clnt_perror(cl,argv[1]);
                    exit(1);
            }            
            printf(" %s\n", *charResult);
            flag=1;
        }

    //  Exécution de LPWD
	if(strcmp(cmd,"lpwd")==0){
            getcwd(path, MAXPATHLEN);
            result=path;
            printf(" %s\n", result);
            flag=1;
        }

    //  Exécution de CD
	if(strcmp(cmd,"cd")==0){
           charArg=args;
           boolResult = cd_1(&charArg, cl);

            if (boolResult == NULL){
                    clnt_perror(cl,argv[1]);
                    exit(1);
            }
           if(*boolResult==0)
            printf("cd: %s: No such directory\n", args);
            flag=1;
        }

    //  Exécution de LCD
	if(strcmp(cmd,"lcd")==0){
             sprintf(cmd, "%s", args);
            if(strcmp(args,"null")==0)
               sprintf(cmd, ".");

            out=chdir(cmd);

            if(out!=0)
                printf("cd: %s: No such directory\n", args);
            flag=1;
        }

    //  Exécution de LS
	if(strcmp(cmd,"ls")==0){
            charArg=args;    
            charResult = ls_1((void *)NULL, cl);
            
            if (charResult == NULL){
                    clnt_perror(cl,argv[1]);
                    exit(1);
            }
  
            if(strcmp(*charResult,"null")==0)
                printf(" lls: %s: No such file or directory\n", args);
            else
                printf("%s\n", *charResult);

            flag=1;
        }

    //  Exécution de LLS
	if(strcmp(cmd,"lls")==0){
        sprintf(cmd, "%s", args);
        if(strcmp(args,"null")==0)
           sprintf(cmd, ".");

        charResult = getdir(cmd);
        if(strcmp(*charResult,"null")==0)
            printf(" lls: %s: No such file or directory\n", args);
        else
            printf("%s\n", *charResult);
        flag=1;
        }

    //  Exécution de get_1
	if(strcmp(cmd,"get")==0){
            charArg=args;
            fileResult = get_1(&charArg, cl);
            if (fileResult == NULL){
                    clnt_perror(cl,argv[1]);
                    printf(" Get unsuccess ...\n");
            }else{
           out =getFile(args,args,cl);
            if (out != 0)
                printf(" Get success ...\n");
            }
          flag=1;
        }

    //  Exécution de put_1
	if(strcmp(cmd,"put")==0){
            charArg=args;
            intResult = put_1(&charArg, cl);
            if (intResult == NULL){                    
                    printf(" put: %s: Permission denied\n",args);
            }else{
            out =putFile(args,args,cl);
            if (out != 0)
                printf(" Put success ...\n");
            }
            flag=1;
        }

    //  Exécution de bye_1
	if(strcmp(cmd,"bye")==0){
            intResult = bye_1((void *)NULL, cl);            
            if (intResult == NULL){                
                    clnt_perror(cl,argv[1]);
                    exit(1);
            }
            if(*intResult==1)
                printf(" Good Bye...\n");
            else
                printf(" Deconnection error...\n");
           break;
        }

    //  Mauvaise commande
	if(strcmp(cmd,"\0")!=0&&flag==0)
            printf(" myFtp: %s: Command not found\n", cmd);
        
    }
    clnt_destroy(cl);

    return (EXIT_SUCCESS);
}

